import React from 'react';
import { InputItem, Button, Toast } from 'antd-mobile';
import { fetchVerifyCode } from '../../services/vipService';
import styles from './VerifyCodeItem.less';

class VerifyCodeItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timer: null,
      timeLimit: 0,
    };
  }

  beginTimeLimit = () => {
    let seconds = 60;
    const timer = setInterval(() => {
      this.setState({
        timeLimit: seconds,
      });
      --seconds;
      if (seconds < 0) {
        clearInterval(timer);
        this.setState({
          timeLimit: 0,
        });
      }
    }, 1000);
    this.setState({
      timer,
    });
  };

  sendVerifyCode = () => {
    Toast.loading();
    const shopId = this.props.shopId;
    const phoneField = this.props.phoneField;
    this.props.form.validateFields([phoneField], (error, value) => {
      if (value[phoneField]) {
        const phone = value[phoneField].replace(/\s/ig, '');
        const data = { type: this.props.codeType };
        if (this.props.reg) {
          data.reg = true;
        }
        if (this.props.bind) {
          data.bind = true;
        }
        fetchVerifyCode(phone, shopId, data).then(() => {
          Toast.hide();
          this.beginTimeLimit();
          Toast.success('验证码发送成功');
        }).catch((e) => {
          Toast.hide();
          Toast.fail('获取验证码失败');
        });
      } else {
        Toast.info('请输入手机号');
      }
    });
  };

  render() {
    const { form: { getFieldProps } } = this.props;
    const codeBtn = (
      <div>
        <Button disabled={this.state.timeLimit > 0} onClick={this.sendVerifyCode} type="primary" size="small">
          {this.state.timeLimit > 0 ? '请等待' + this.state.timeLimit + '秒' : '获取验证码'}
        </Button>
      </div>
    );

    return (
      <InputItem
        className={`verifyCodeItemWrapper ${styles.verifyCodeItem}`}
        {...getFieldProps(this.props.fieldName, {
          rules: [{ required: true, message: '请输入验证码' }],
        })}
        type="number"
        placeholder=""
        extra={codeBtn}
      >验证码</InputItem>
    );
  }
}

VerifyCodeItem.propTypes = {
  codeType: React.PropTypes.string, // 3 - 会员卡, 4 - 新增会员
  phoneField: React.PropTypes.string,
  fieldName: React.PropTypes.string,
  form: React.PropTypes.object,
  shopId: React.PropTypes.string,
  reg: React.PropTypes.bool,
  bind: React.PropTypes.bool,
};

VerifyCodeItem.defaultProps = {
  reg: false,
  bind: false,
  codeType: '3',
  phoneField: 'mobile',
  fieldName: 'verifyCode',
};

export default VerifyCodeItem;
